package site.luojie;

import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;

/**
 * @author jie.luo
 * @since 2020-08-13
 */
public class DruidDataSourceFactory {

    private static Logger logger = LoggerFactory.getLogger(DruidDataSourceFactory.class);

    public static DruidDataSource dataSource = null;

    public static DruidDataSource build(DataSourceInfo dataSourceInfo, boolean restart) throws SQLException {

        logger.debug("构建数据源.......{}", dataSourceInfo);

        if (restart) {
            logger.debug("重新构建数据源.......释放连接");
            dataSource.restart();
        } else {
            dataSource = new DruidDataSource();
        }

        // 基本配置
        dataSource.setUsername(dataSourceInfo.getUsername());
        dataSource.setPassword(dataSourceInfo.getPassword());
        dataSource.setUrl(dataSourceInfo.getUrl());

        // 配置初始化大小、最小、最大
        dataSource.setInitialSize(dataSourceInfo.getInitialSize());
        dataSource.setMinIdle(dataSourceInfo.getMinIdle());
        dataSource.setMaxActive(dataSourceInfo.getMaxActive());

        dataSource.init();
        return dataSource;
    }

}
